package org.celery.client.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.celery.common.config.WxMaConfiguration;
import org.celery.common.utils.MemberTokenUtil;
import org.celery.core.secure.MemberAuthInfo;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.enums.UserStatusEnum;
import org.springblade.modules.system.service.IUserService;
import org.springframework.web.bind.annotation.*;


/**
 * Create on 2021-11-22
 *
 * @author Celery <1031868928@qq.com>
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wechat/{appid}")
@Slf4j
@Api(value = "微信", tags = "移动端 - 微信相关接口")
public class ClientWechatController {

    @PostMapping(value = "greet")
    public R<WxMaJscode2SessionResult> greet(@PathVariable String appid, String jsCode) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
            return R.data(wxService.jsCode2SessionInfo(jsCode));
        } catch (WxErrorException e) {
            throw new ServiceException("微信登录失败");
        }
    }

    @PostMapping(value = "login")
    public R<MemberAuthInfo> login(@RequestParam String openId) {
        IUserService userService = SpringUtil.getBean(IUserService.class);
        User member = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getOpenId, openId));

        if (member == null) {
            return R.fail(TokenUtil.USER_NOT_FOUND);
        }

        if (member.getStatus().equals(UserStatusEnum.APPLYING.getStatus())) {
            throw new ServiceException("请等待管理员审核!");
        }

        if (member.getStatus().equals(UserStatusEnum.REFUSE.getStatus())) {
            throw new ServiceException("账号受限无法登录!");
        }

        return R.data(MemberTokenUtil.createAuthInfo(member));
    }
}
